// 自动识别 表单内的 控件，把它们初始化
define(function(require, exports, module) {
	var $ = require('bigfoot/common'),
		_uploadUtils = require('bigfoot/widget/upload/ui'),
		_calendar = require('bigfoot/dhtml/form/calendar');
   
   /*------------------------------------
     -----------------------------------
    				日历
     -----------------------------------
    ------------------------------------*/
	exports.initCalendar = initCalendar;
	function initCalendar(formEl){
	    
	    // 自动扫描 DOM 是否有 日历控件的 Markup，有就初始化
        var cale, calendarEls = $.hook('.Calendar', true);
       
        for(var i = 0, j = calendarEls.length; i < j; i++){
            cale = Object.create(_calendar);
            cale.el = calendarEls[i];
            cale.onSelect = initCalendar.onSelect.bind(calendarEls[i]);
            cale.init();
        }
	}

	initCalendar.onSelect = function(date){
        var input = this.parentNode.$('input[type=text]');
        // 时间要有限制，不能选择当前日期之前的时间
        var noSelectedBeforeDate = input.getAttribute('noSelectedBeforeDate');

        // 2012-07-08
        // firefox中解析 new date(2012/12-23) 不兼容，提示invalid date 无效的日期
		// Chrome下可以直接将其格式化成日期格式，且时分秒默认为零
        var arr = date.split('-'), now = new Date(arr[0], arr[1] - 1, arr[2], " ", " ", " ");
        if (noSelectedBeforeDate == "true" && now < new Date){
        	$.alert('不能选择当前日期之前的时间');
        }else {
        	input.value = date;
        }
    }

   /*------------------------------------
     -----------------------------------
    			图片本地预览
     -----------------------------------
    ------------------------------------*/
	exports.initImgPerview = initImgPerview;
	function initImgPerview(formEl, onUpload_Done){

	    formEl.$('.imgUpload', function(imgUpload){
	    	// 提交到上传 专用表单
	    	imgUpload.$('.uploadAction').$(_uploadUtils.onUploadBtnClk);
	    	_uploadUtils.perviewImg(imgUpload.$('input[type=file]'), imgUpload.$('.perview img'));
	    });

        // 登记 onload 事件，只需一次，所以使用 onload
        var uploadIframe = $('iframe[name=uploadIframe]');
        if(uploadIframe)uploadIframe.onload = initImgPerview.onUoload_OK.after(onUpload_Done || appendPic_HiddenField);		
	}
	initImgPerview.onUoload_OK = function(e){
        var json = e.target.contentDocument.body.innerHTML;
        json = JSON.parse(json);

        if(json.success){
        	$.msg('图片上传成功');

        	return json;
        }else $.alert('上传失败！原因：' + e.target.contentDocument.body.innerHTML);
    }

    function appendPic_HiddenField(json){
    	// 如果有返回 字段域的 hidden input 之 CSS Selector，则设置其 value
	    if(json.uiName){
	    	$(json.uiName).value = json.fileName;
	    }
    }

   /*------------------------------------
     -----------------------------------
    			剩余字数提示
     -----------------------------------
    ------------------------------------*/
    exports.whenpresscheckCharLength = whenpresscheckCharLength;
    function whenpresscheckCharLength(formEl){
    	var whenpresscheckCharLength = formEl.$('.whenpresscheckCharLength');
    	if (whenpresscheckCharLength != bf.emptyObj){
	    	var _for = whenpresscheckCharLength.getAttribute('for'),
	    		showRemainCharLength = formEl.$('.' + _for);
    		var charLimit = whenpresscheckCharLength.hasAttribute('charLimit') ? whenpresscheckCharLength.getAttribute('charLimit') :20; 

    		var inputed = whenpresscheckCharLength.value.length;

    		if(inputed > 0){
    			showRemainCharLength.innerHTML = String(charLimit - inputed);
    		}else showRemainCharLength.innerHTML = String(charLimit);
		
		    function handler(e){
				var pressedLength = whenpresscheckCharLength.value.length,
					left = charLimit - pressedLength;
				
				if((left + 1) <= 0){
					e.preventDefault();
					shake(whenpresscheckCharLength, 'red');
				}else showRemainCharLength.innerHTML = String(left);
				// console.log(charLimit - pressedLength);
			}

    		whenpresscheckCharLength.onkeyup = whenpresscheckCharLength.onpaste = handler;
    	}
    } 


	function shake(ele, cls, times) {
		var i = 0, times = times || 2;
		ele.addCls(cls);
		var t = window.setInterval(function(){
			i++;
			ele.removeCls(cls);
			if(i % 2)ele.addCls(cls);
			if (i == 2 * times) {
				window.clearInterval(t);
				ele.removeCls(cls);
			}
		}, 150);
	}
});